package filesystem

import (
	"io/fs"
	"io/ioutil"
	"os"
	"path/filepath"
	"sort"
	"strings"
)

// ListDir 获取指定目录下的所有文件，不进入下一级目录搜索，可以匹配后缀过滤。
func ListDir(dirPth string, suffix string) (files []string, err error) {
	files = make([]string, 0, 10)
	var (
		fileInfos []fs.FileInfo
	)
	if fileInfos, err = ioutil.ReadDir(dirPth); err != nil {
		return
	}

	PthSep := string(os.PathSeparator)
	suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写

	for _, fi := range fileInfos {
		if fi.IsDir() { // 忽略目录
			continue
		}
		if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) { //匹配文件
			files = append(files, dirPth+PthSep+fi.Name())
		}
	}
	if files != nil && len(files) > 0 {
		//排序
		sort.Slice(files, func(i, j int) bool {
			if len(files[i]) == len(files[j]) {
				return files[i] < files[j]
			} else {
				return len(files[i]) < len(files[j])
			}
		})
	}

	return
}

// WalkDir 获取指定目录及所有子目录下的所有文件，可以匹配后缀过滤。
func WalkDir(dirPth, suffix string) (files []string, err error) {
	files = make([]string, 0, 30)
	suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写

	err = filepath.Walk(dirPth, func(filename string, fi os.FileInfo, err error) error { //遍历目录
		//if err != nil { //忽略错误
		// return err
		//}

		if fi.IsDir() { // 忽略目录
			return nil
		}

		if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) {
			files = append(files, filename)
		}

		return nil
	})

	return
}

// ShouldIgnored2 应该忽略
func ShouldIgnored2(filePath, ignoreFile string) (ignore bool, err error) {
	var (
		resultLines []string
	)
	if resultLines, err = GetFileLines(ignoreFile, true); err != nil {
		return
	}
	dir := filepath.Dir(ignoreFile)
	for _, line := range resultLines {
		var (
			matches []string
		)
		if !strings.Contains(line, dir) {
			line = strings.Join([]string{
				dir, line}, "\\")
		}
		matches, err = filepath.Glob(line)
		for _, match := range matches {
			ignore = strings.Contains(filePath, match)
			if ignore {
				return
			}
		}
	}
	return
}

const (
	IgnoreFileName = ".file_process_ignore"
)

func FindIgnoreFile(dir string) (resultFile string, err error) {
	dir = strings.TrimSpace(dir)
	if dir == "" {
		return
	}
	var (
		isDirectory bool
		directory   string
		ignoreFile  string
		existed     bool
	)
	//dir是否目录
	isDirectory = IsDir(dir)
	if isDirectory {
		directory = dir
	} else {
		directory = filepath.Dir(dir)
	}
	ignoreFile = filepath.Join(directory, IgnoreFileName)
	if existed, err = PathExists(ignoreFile); existed && err == nil {
		resultFile = ignoreFile
		return
	} else if directory != "" && isDirectory && !IsRootDir(directory) {
		//不是根目录
		directory = filepath.Dir(dir)
		return FindIgnoreFile(directory)
	}
	return
}
